package blazingbubble.network.game.strategy;

import blazingbubble.game.Game;
import blazingbubble.game.Player;
import moltencore.network.protocol.JoinGameResponse;
import moltencore.network.protocol.PlayerData;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.network.protocol.Base;
import spark.network.protocol.Acknowledgement;
import org.apache.log4j.Logger;
import spark.utility.OutWrapper;

import java.util.Collection;

public class JoinGameResponseStrategy implements IProtocolHandleStrategy<JoinGameResponse> {
	private Logger logger = Logger.getLogger(JoinGameResponseStrategy.class);

	private IJoinGameResponseResultListener joinGameResponseResultListener;
	private Game game;

	public JoinGameResponseStrategy(IJoinGameResponseResultListener joinGameResponseResultListener, Game game) {
		this.joinGameResponseResultListener = joinGameResponseResultListener;
		this.game = game;
	}

	@Override
	public void handle(JoinGameResponse packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		logger.info("JoinGameResponseStrategy: accepted " + packet.getAccepted() + "; message " + new String(packet.getMessage()));
		if(packet.getAccepted()) {
			joinGameResponseResultListener.joinSuccessful();
			for(PlayerData playerData : packet.getJoinedPlayers()) {
				Player player = new Player(playerData.getName(), playerData.getClientId());
				player.setBubbleSetId(playerData.getBubbleSetId());
				game.addPlayer(player);
			}
		}
		else {
			joinGameResponseResultListener.joinFailed(new String(packet.getMessage()));
		}
		acknowledgement.value = new Acknowledgement(packet);
	}
}